package cn.tedu.store.service.impl;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.tedu.store.entity.Address;
import cn.tedu.store.entity.Cart;
import cn.tedu.store.mapper.CartMapper;
import cn.tedu.store.service.ICartService;
import cn.tedu.store.service.ex.AccessDeniedException;
import cn.tedu.store.service.ex.CartNotFoundException;
import cn.tedu.store.service.ex.InsertException;
import cn.tedu.store.service.ex.UpdateException;
import cn.tedu.store.vo.CartVO;
@Service
public class CartServiceImpl implements ICartService {

	@Autowired
	private CartMapper cartMapper;
	
    private void insert(Cart cart) throws InsertException {
    	Integer row=cartMapper.insert(cart) ;
    	if(row!=1) {
    		throw new InsertException("购物车插入数据异常");
    	}
    }
	
	private void updateNum(Integer cid, Integer num, String modified_user,Date modified_time) 
		throws UpdateException {
		Integer rows=cartMapper.updateNum(cid, num, modified_user, modified_time);
		if(rows!=1) {
    		throw new UpdateException("购物车更新商品数量异常");
    	}
	}

	private Cart findByUidAndGid(Integer uid,Long gid) {
		return cartMapper.findByUidAndGid(uid, gid);
	}
	
	@Override
	public void addToCart(Cart cart, Integer uid, String username) throws InsertException, UpdateException {
		Cart result=findByUidAndGid(uid,cart.getGid());
		Date now=new Date();
		if (result==null) {
			cart.setUid(uid);
			cart.setCreated_user(username);
			cart.setModified_user(username);
			cart.setCreated_time(now);
			cart.setModified_time(now);
			insert(cart);
		}else {

			updateNum(result.getCid(),result.getNum()+cart.getNum(),username,now);
		}

	}

	@Override
	public List<CartVO> getByUid(Integer uid) {
		
		return findByUid(uid);
	}
	
	private List<CartVO> findByUid(Integer uid){
	    return cartMapper.findByUid(uid);
	}

	private Cart findByCid(Integer cid) {
		return cartMapper.findByCid(cid);
	}

	@Override
	public Integer add(Integer cid, Integer uid, String username)
			throws CartNotFoundException, AccessDeniedException, UpdateException {
		Cart result=findByCid(cid);
		if (result==null) {
			throw new CartNotFoundException("购物车数据不存在！");
		}
		if(result.getUid()!=uid) {
			throw new AccessDeniedException("增加购物车数量失败！");
		}
			Integer newNum=result.getNum()+1;
			cartMapper.updateNum(cid, newNum, username,new Date());
		return newNum;
	}
	
	
	private List<CartVO> findByCids(Integer[] cids){
		return cartMapper.findByCids(cids);
	}

	@Override
	public List<CartVO> getByCids(Integer[] cids,Integer uid) throws CartNotFoundException, AccessDeniedException {
		
		List<CartVO> results=findByCids(cids);
		//需要移除list中的项目，必须用迭代器，不能用foreach
		Iterator<CartVO> it=results.iterator();
		while(it.hasNext()){
		if(uid!=it.next().getUid()){
		    it.remove();
		  }
		}
		return results;
	}
}
